package com.board.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.board.dao.UserInfoMapper;
import com.board.dto.UserDto;
import com.board.dto.UserInfoDto;
import com.board.entity.UserInfo;
import com.board.param.LoginByPassParam;
import com.board.service.UserInfoService;
import com.board.util.StateDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小叶
 * @since 2024年04月08日
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfoDto loginByPass(LoginByPassParam param, HttpServletRequest request) {
        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        wrapper.eq("user_phone",param.getUserPhone());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        //判断查没查到账户
        if (ObjectUtil.isEmpty(userInfo)){
            throw new RuntimeException("账号错误");
        }
        //密码是否正确
        System.out.println(userInfo.getUserPass());
        System.out.println(param.getUserPassword());
        if (!userInfo.getUserPass().equals(param.getUserPassword())){
            throw new RuntimeException("密码错误");
        }
        //登录状态是不是0，0为正常
        if (userInfo.getUserState()!= StateDate.USER_STATE_NORMAL){
            throw new RuntimeException("状态错误");

        }
        //生成登录日志
//        String ip = ipUtil.getIp(request);
//        UserLogInfo userLogInfo = new UserLogInfo();
//        userLogInfo.setLoginIp(ip);
//        LocalDateTime currentTime = LocalDateTime.now();
//        userLogInfo.setLoginTime(currentTime);
//        userLogInfo.setUserName(userInfo.getUserPhone());
//        userLogInfo.setUserId(userInfo.getUserId());
//        userLogInfoMapper.insert(userLogInfo);
        //返回对象
        UserInfoDto userInfoDto = BeanUtil.toBean(userInfo, UserInfoDto.class);
        return userInfoDto;
    }

    @Override
    public UserDto findUserById(Integer userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        if (userInfo==null) throw new RuntimeException("用户不存在");
        UserDto dto = BeanUtil.toBean(userInfo, UserDto.class);

        return dto;
    }
}
